package com.bankfourfactor.nanyun;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.bankfourfactor.BankCarFactoryConstant;
import com.ny.lib.NyHttpClient;
import com.ny.lib.NyPropertiesUtil;
import com.ny.lib.NySignatureStrUtil;
import com.ny.lib.NyVerifySignature;

import net.sf.json.JSONObject;

public class NyBase {
	public static String encoding = "UTF-8";

	/**
	 * java main方法 数据提交 提交到后台
	 * 
	 * @param contentData
	 * @return 返回报文 map
	 */
	public static Map<String, String> submitUrl(Map<String, String> submitFromData, String requestUrl) {
		String resultString = "";
		
		System.out.println("requestUrl====" + requestUrl);
		System.out.println("submitFromData====" + submitFromData.toString());
		
		NyHttpClient hc = new NyHttpClient(requestUrl, 30000, 30000);//http请求
		String info1 = getRequestParamString(submitFromData, encoding);//数据进行转码
		System.out.println(info1 + "========================");
		//todo Map使用多态写法
		HashMap<String, String> resData = new HashMap<String, String>();
		try {
			int status = hc.send(submitFromData, encoding);
			// if (200 == status) {
			System.out.println("http响应码====" + status);
			resultString = hc.getResult();
			System.out.println("返回结果====" + resultString);
			// }
			resData = toHashMap(resultString);//json转换成map集合
			NyVerifySignature verifySignature = new NyVerifySignature();
			/**
			 * 验证签名
			 */
			if (null != resultString && !"".equals(resultString)) {
				String info = NySignatureStrUtil.getVerSignatureString(resData);
				// 获取公钥
				//String pubKey = NyPropertiesUtil.getSrcProperty(propertyName, "nyPubKey");
				String sig = resData.get("sign");
				Boolean result = verifySignature.run(info,BankCarFactoryConstant.NANYUN_PUBLIC_KEY, sig);
				if (result) {
					System.out.println("验证签名成功====================");
				} else {
					System.out.println("验证签名失败====================");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return resData;
	}
	//todo Map使用多态写法
	private static HashMap<String, String> toHashMap(Object object) {
		HashMap<String, String> data = new HashMap<String, String>();
		// 将json字符串转换成jsonObject
		JSONObject jsonObject = JSONObject.fromObject(object);
		Iterator it = jsonObject.keys();
		// 遍历jsonObject数据，添加到Map对象
		while (it.hasNext()) {
			String key = String.valueOf(it.next());
			String value = (String) jsonObject.get(key);
			data.put(key, value);
		}
		return data;
	}

	private static String getRequestParamString(Map requestParam, String coder) {
		if (null == coder || "".equals(coder))
			coder = "UTF-8";
		StringBuffer sf = new StringBuffer("");
		String reqstr = "";
		if (null != requestParam && 0 != requestParam.size()) {
			Iterator i$ = requestParam.entrySet().iterator();
			do {
				if (!i$.hasNext())
					break;
				java.util.Map.Entry en = (java.util.Map.Entry) i$.next();
				try {
					sf.append((new StringBuilder()).append((String) en.getKey()).append("=")
							.append(null != en.getValue() && !"".equals(en.getValue())
							? URLEncoder.encode((String) en.getValue(), coder) : "").append("&").toString());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					return "";
				}
			} while (true);
			reqstr = sf.substring(0, sf.length() - 1);
		}
		return reqstr;
	}

	private static Map<String, String> formatResponseToMap(String response) {
		Map<String, String> data = new HashMap<String, String>();
		response = response.substring(0, response.length());
		String[] results = response.split("&");
		for (String li : results) {
			data.put(li.split("=")[0], li.split("=")[1]);
		}
		return data;
	}
}
